package com.lz.netty.producer.project.api.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.lz.netty.producer.NettyProducerApplication;
import com.lz.netty.producer.common.domain.RequestVo;
import com.lz.netty.producer.common.domain.ResponseVo;
import com.lz.netty.producer.common.utils.DateUtils;
import com.lz.netty.producer.project.api.service.ApiService;
import com.lz.netty.producer.project.netty.ChannelStore;
import com.lz.netty.producer.project.netty.util.MsgUtil;
import io.netty.buffer.CompositeByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.DefaultFileRegion;
import io.netty.util.CharsetUtil;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;


/**
 * 服务端请求 测试
 *
 * @author xpp
 */
@RestController
@RequestMapping("/api")
public class ApiController {

    private static final Logger logger = LoggerFactory.getLogger(ApiController.class);

    @PostMapping("/nettyServer")
    public ResponseVo checkThread(@RequestBody RequestVo requestVo) {
        sendOneMsg(StrUtil.format("服务端,发送消息:{},日期:{}:", JSONUtil.toJsonStr(requestVo), DateUtils.getCurr_YYYY_MM_DD_HH_MM_SS_SSS() + "\r\n"));
        return ResponseVo.success();
    }

    @GetMapping("/nettyS2")
    public ResponseVo nettyC2() {
        sendOneMsg(StrUtil.format("服务端发送,日期:{}", DateUtils.getCurr_YYYY_MM_DD_HH_MM_SS_SSS() + "\r\n"));
        return ResponseVo.success();
    }

    /**
     * 发送消息
     */
    public static void sendOneMsg(String msg) {
        for (Channel channel : ChannelStore.CHANNEL_GROUP) {
            channel.writeAndFlush(MsgUtil.buildMsg(channel.id().toString(), msg));
            channel.writeAndFlush(MsgUtil.buildMsg(channel.id().toString(), msg)).addListener((ChannelFutureListener) future -> {
                if (future.cause() != null) {
                    logger.error("服务端netty消息发送失败:", future.cause());
                } else if (future.isSuccess()) {
                    logger.info("服务端netty消息发送成功:{}", msg);
                } else {
                    logger.error("服务端Message send failed for an unknown reason.");
                }
            });
        }
    }
}
